package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @author jinpei
 * @version v1.0
 * @date 2019/5/5 19:25
 * @description TODO
 **/
@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    public List<CategoryDTO> queryCategoryByParentId(Long pid) {
        // 根据父类目的id查询子类目
        Category category = new Category();
        category.setParentId(pid);
        List<Category> categoryList = categoryMapper.select(category);
        // 健壮性判断
        if (CollectionUtils.isEmpty(categoryList)) {
            // 返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 使用自定义工具类，把Category集合转为DTO的集合
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }

    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {
        List<Category> categoryList = categoryMapper.queryCategoryByBrandId(brandId);
        // 健壮性判断
        if (CollectionUtils.isEmpty(categoryList)) {
            // 返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 使用自定义工具类，把Category集合转为DTO的集合
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }

    public List<CategoryDTO> queryByIds(List<Long> ids) {
        // 分类查询
        List<Category> categoryList = categoryMapper.selectByIdList(ids);
        // 健壮性判断
        if (CollectionUtils.isEmpty(categoryList)) {
            // 返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 使用自定义工具类，把Category集合转为DTO的集合
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }

    public List<CategoryDTO> queryAllByCid3(Long id) {
        Category c3 = categoryMapper.selectByPrimaryKey(id);
        if (c3 == null) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        Category c2 = categoryMapper.selectByPrimaryKey(c3.getParentId());
        if (c2 == null) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        Category c1 = categoryMapper.selectByPrimaryKey(c2.getParentId());
        if (c1 == null) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        List<Category> list = Arrays.asList(c1, c2, c3);
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }
}
